import { defineStore } from "pinia"
import { ref } from "vue"


// 游戏数据及方法
export const useDataStore = defineStore('data', () => {
    const canvasSizeWidth = 900;
    const canvasSizeHeight = 600;
    const cellSize = 20;
    const canvasRef = ref(null); // 获取画布和上下文
    const ctxRef = ref(null);
    const speed = ref(3);
    const scoreRef = ref(0);
    const gameOverRef = ref(false);
    const startShowRef = ref(true);
    const textPower = ref('');
    const powerRef = ref(false);
    const onClick = ref(false);
    const foodPosition = ref({ x: 5, y: 5 }); // 食物的位置
    let snakeBody = ref();
    const direction = ref({ x: 0, y: 1 }); // 贪吃蛇的头部方向
    const lastKeyDown = ref(null)

    // 移动蛇
    const moveSnake = () => {
        const head = {x: snakeBody.value[0].x + direction.value.x, y: snakeBody.value[0].y + direction.value.y};
        snakeBody.value.unshift(head);
        snakeBody.value.pop();
    };

    const initSnakeBody = () => {
        snakeBody = ref([
            { x: 20, y: 10 },
            { x: 20, y: 10 },
            { x: 20, y: 10 },
          ]);
    }


    // 设置画布大小
    const setCanvasSize = () => {
        canvasRef.value.width = canvasSizeWidth;
        canvasRef.value.height = canvasSizeHeight;
    }

    // 渲染蛇和食物到画布上
    const render = () =>  {
        ctxRef.value.fillStyle = 'black';
        ctxRef.value.fillRect(0, 0, canvasSizeWidth, canvasSizeHeight);
        snakeBody.value.forEach((part) => {
        ctxRef.value.fillStyle = 'green';
        ctxRef.value.fillRect(part.x * cellSize, part.y * cellSize, cellSize - 2, cellSize - 2);
        })
    
        ctxRef.value.fillStyle = 'red';
        ctxRef.value.fillRect(foodPosition.value.x * cellSize, foodPosition.value.y * cellSize, cellSize, cellSize);
    }

    // 使用技能
    const usePower = () => {
        const increase = speed.value * 0.60;
        const powerNum = Math.round(Math.random() * 10) % 3;
        switch (powerNum) {
          case 0:
            textPower.value = "加速5秒";
            speed.value += increase;
            setTimeout(() => speed.value -= increase ,5000);
            break;
          case 1:
            textPower.value = "加200分";
            scoreRef.value += 200;
            break;
          case 2:
            textPower.value = "蛇蛇收缩";
            snakeBody.value = snakeBody.value.slice(0, 3);
            speed.value += 5;
            break;
        }
      }

      
    // 生成食物
    const spawnFood = () => {
        foodPosition.value = {
          x: Math.floor(Math.random() * (canvasSizeWidth / cellSize)),
          y: Math.floor(Math.random() * (canvasSizeHeight / cellSize)),
        };
    };


    // 检查碰撞
    const checkCollisions = () => {
        const head = snakeBody.value[0];
    
        // 检查是否吃到食物
        if (head.x === foodPosition.value.x && head.y === foodPosition.value.y) {
        scoreRef.value += 20;
        // 获取 power
        if(scoreRef.value % 100 == 0){
            textPower.value = "【POWER】"
            powerRef.value = true;
        }
        snakeBody.value.push({x: snakeBody.value.at(-1).x - direction.value.x, y: snakeBody.value.at(-1).y - direction.value.y});
        spawnFood();
        } 
    
        // 检查是否撞到自己
        for (let i = 3; i < snakeBody.value.length; i++) {
        if (head.x === snakeBody.value[i].x && head.y === snakeBody.value[i].y) {
            gameOverRef.value = true;
        }
        }
        
        // 检查是否撞到墙
        if (head.x < 0 || head.x >= canvasSizeWidth / cellSize || head.y < 0 || head.y >= canvasSizeHeight / cellSize) {
        gameOverRef.value = true;
        }
    };

    // 游戏循环
    const gameLoop = () => {
        if (!gameOverRef.value) {
        if(!onClick.value){
            moveSnake();
        }
        onClick.value = false;
        checkCollisions();
        render();
        setTimeout(gameLoop, 300 - speed.value * 50);
        }
    };

    // 初始化游戏
    const initGame = () => {
        setCanvasSize();
        ctxRef.value = canvasRef.value.getContext('2d');
        initSnakeBody();
        spawnFood();
        gameLoop();
    }

    // 监听键盘事件以改变蛇的方向
    const handleKeyDown = (event) => {
        if (gameOverRef.value) return;
      
        const currentTime = new Date().getTime();
        // 设置一个10毫秒的间隔，只有在至少10毫秒后再次按下相同键时，才触发事件
        if (currentTime - (lastKeyDown.value || 0) > 20){ {
          lastKeyDown.value = currentTime;
        }
      
          if (event.code === 'Space') {
            if (powerRef.value) {
              powerRef.value = false;
              usePower();
              setTimeout(() => {
                textPower.value = '';
              }, 5000);
            }
            return; // 避免执行下面的键位控制逻辑
          }
      
          const newDirection = {
            'ArrowUp': { x: 0, y: -1 },
            'ArrowDown': { x: 0, y: 1 },
            'ArrowLeft': { x: -1, y: 0 },
            'ArrowRight': { x: 1, y: 0 },
          }[event.key];
      
          if (newDirection) {
            // 确保不会设置一个相反的方向
            if (!(
              (newDirection.x === -direction.value.x && newDirection.y === direction.value.y) ||
              (newDirection.x === direction.value.x && newDirection.y === -direction.value.y)
            )) {
              direction.value = newDirection;
              onClick.value = true
              moveSnake();
            }
          }
        }
      };

    const handleRestart = () => {
        // 重置游戏状态
        startShowRef.value = false;
        gameOverRef.value = false;
        powerRef.value = false;
        scoreRef.value = 0;
        textPower.value = '';
        initGame();
      }

    return {
        canvasRef,
        speed,
        scoreRef,
        gameOverRef,
        startShowRef,
        textPower,

        initGame,
        handleKeyDown,
        handleRestart
    }
})